package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.domain.system.Dept;
import com.itheima.mapper.system.DeptMapper;
import com.itheima.service.DeptService;
import com.itheima.utils.MapperUtil;
import com.itheima.utils.UidUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class DeptServiceImpl implements DeptService {
    //查询所有并分页
    @Override
    public List<Dept> findAll(String pageNum,String pageSize) {
        SqlSession session= MapperUtil.getSession();
        DeptMapper mapper = session.getMapper(DeptMapper.class);
        int pageN=1;
        int pageS=10;
        if(StringUtils.isNotBlank(pageNum)){
            pageN=Integer.parseInt(pageNum);
        }
        if(StringUtils.isNotBlank(pageSize)){
            pageS=Integer.parseInt(pageSize);
        }
        PageHelper.startPage(pageN,pageS);
        List<Dept> list=mapper.findAll();
        MapperUtil.close(session);
        return list;
    }
    //查询所有上级部门名称
    @Override
    public List<Dept> list() {
        SqlSession session= MapperUtil.getSession();
        DeptMapper mapper = session.getMapper(DeptMapper.class);
        List<Dept> list=mapper.findAll();
        MapperUtil.close(session);
        return list;
    }
    //新增
    @Override
    public void save(Dept dept) {
        SqlSession session= MapperUtil.getSession();
        DeptMapper mapper = session.getMapper(DeptMapper.class);
        String id = UidUtil.getUid();
        dept.setId(id);
        mapper.save(dept);
        MapperUtil.close(session);
    }
    //删除
    @Override
    public boolean deleteByIds(String id) {
        SqlSession session=null;
        boolean flag=false;//因为有外键关联,所以可能会删除失败
        try {
            session = MapperUtil.getSession();
            DeptMapper mapper = session.getMapper(DeptMapper.class);
            String[] idArray = id.split(",");
            mapper.deleteByIds(idArray);
            flag=true;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MapperUtil.close(session);
        }
        return flag;
    }

    @Override
    public Dept findById(String id) {
        SqlSession session= MapperUtil.getSession();
        DeptMapper mapper = session.getMapper(DeptMapper.class);
        Dept dept=mapper.findById(id);
        MapperUtil.close(session);
        return dept;
    }

    @Override
    public void update(Dept dept) {
        SqlSession session= MapperUtil.getSession();
        DeptMapper mapper = session.getMapper(DeptMapper.class);
        mapper.update(dept);
        MapperUtil.close(session);
    }
}
